package cn.itsource.ymcc.schedu;

import cn.itsource.ymcc.domain.KillCourse;
import cn.itsource.ymcc.service.IKillCourseService;
import cn.itsource.ymcc.util.StrUtils;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.itsource.ymcc.constant.RedisConstants.KILL_ACTIVITY_KEY;

@Component
@Slf4j
//@EnableAsync
public class KillCourserPublishTask {

    @Autowired
    private IKillCourseService killCourseService;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    // 0 0 2 * * ?// 正在上线之后的 表达式
   // @Scheduled(cron = "0/10 * * * * ?")
   // @Scheduled(cron = "0/10 * * * * ?")
    //@Async
    public void publish(){
        log.info("开启定时任务，去查询需要上架的活动课程");
        List<KillCourse> shuldKillCourse = killCourseService.getShuldKillCourse();

        log.info("查询出，待上架的商品：{}",shuldKillCourse);

        if(shuldKillCourse==null||shuldKillCourse.size()<0){
            return;
        }
        Date date = new Date();
        // 上架- <"Killactivity":Map<killCourseID,killCourse>> 保存到redis中
        for (KillCourse killCourse : shuldKillCourse) {
            Map<String,KillCourse> map = new HashMap<>();

            // 活动验证的描述码
            killCourse.setKillCode(StrUtils.getRandomString(4));

            map.put(killCourse.getId().toString(),killCourse);
            redisTemplate.boundHashOps(KILL_ACTIVITY_KEY).putAll(map);

            // redis 信号量就是上架商品的库存
            RSemaphore semaphore = redissonClient.getSemaphore("killId:" + killCourse.getId());
            semaphore.trySetPermits(killCourse.getKillCount());

            // 修改数据中 活动商品的信息 上架状态 和 发布时间
            killCourse.setPublishStatus(KillCourse.BEFORE_KILLING);
            killCourse.setPublishTime(date);

            killCourseService.updateById(killCourse);
        }
        log.info("待上架完成");
    }
}
